package com.jl.core.util.file;

import com.jl.utils.ImageToBase64;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.*;
import java.util.Date;

@Component
@Data
@Slf4j
public class FileUtil {

    private static String destFile = "/root/photo/";

//    private static String destFile = "d:\\test\\";

    private static String destUrl = "/photo/";

    /*
    文件上传
     */
    public String upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        String path = destFile+"/"+originalFilename;
        File dest = new File(path);
        try {
            if (!dest.exists()){
                dest.mkdirs();
            }
            file.transferTo(dest);
            return path;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
    下载URI文件
     */
    public static File downloadFile(String urlPath, String downloadDir) {
        File file = null;
        try {
            // 统一资源
            URL url = new URL(urlPath);
            // 连接类的父类，抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            //设置超时
            httpURLConnection.setConnectTimeout(1000*5);
            //设置请求方式，默认是GET
            httpURLConnection.setRequestMethod("POST");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打开到此 URL引用的资源的通信链接（如果尚未建立这样的连接）。
            httpURLConnection.connect();
            // 文件大小
            int fileLength = httpURLConnection.getContentLength();

            // 控制台打印文件大小
            System.out.println("您要下载的文件大小为:" + fileLength / (1024 * 1024) + "MB");

            // 建立链接从请求中获取数据
            URLConnection con = url.openConnection();
            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
            // 指定文件名称(有需求可以自定义)
            String fileFullName = "aaa.apk";
            // 指定存放位置(有需求可以自定义)
            String path = downloadDir + File.separatorChar + fileFullName;
            file = new File(path);
            // 校验文件夹目录是否存在，不存在就创建一个目录
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            OutputStream out = new FileOutputStream(file);
            int size = 0;
            int len = 0;
            byte[] buf = new byte[2048];
            while ((size = bin.read(buf)) != -1) {
                len += size;
                out.write(buf, 0, size);
                // 控制台打印文件下载的百分比情况
                System.out.println("下载了-------> " + len * 100 / fileLength + "%\n");
            }
            // 关闭资源
            bin.close();
            out.close();
            System.out.println("文件下载成功！");
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("文件下载失败！");
        } finally {
            return file;
        }
    }

    public static String GetImageStr(String imgFilePath) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;

        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgFilePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);// 返回Base64编码过的字节数组字符串
    }

    /**
     * base64字符串转化成图片
     *
     * @param imgData
     *            图片编码
     * @param imgFilePath
     *            存放到本地路径
     * @return
     * @throws IOException
     */
    @SuppressWarnings("finally")
    public static boolean GenerateImage(String imgData, String imgFilePath) throws IOException { // 对字节数组字符串进行Base64解码并生成图片
        if (imgData == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            out = new FileOutputStream(imgFilePath);
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgData);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            out.write(b);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
            return true;
        }
    }

//    public static void downFile(String path, HttpServletResponse response) throws Exception {
//        File file = new File(path);
//        String name = file.getName();
////        String suffix = name.split("\\.")[1];
//        FileInputStream fileInputStream = new FileInputStream(file);
//        response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(name, "UTF-8"));
//        OutputStream outputStream = response.getOutputStream();
//        byte[] bytes = new byte[2048];
//        int len = 0;
//        while ((len = fileInputStream.read(bytes))>0){
//            outputStream.write(bytes,0,len);
//        }
//        fileInputStream.close();
//        outputStream.close();
//    }

    public static void downFile(String path, HttpServletResponse response) throws Exception {
        File file = new File(path);
        String name = file.getName();
//        String suffix = name.split("\\.")[1];
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();

        response.reset();
        response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(name, "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    }

//    public static void main(String[] args) throws IOException {
////        File file = downloadFile("http://thirdwx.qlogo.cn/mmopen/vi_32/OTZ1icFh69VFt7FbL2a7t8lFMT7jFthl5ibDicSST6JOCCxt5X3SZuw9icicJ7YIjib0pw0Bf0ct1RXzXfj2dn6RJkgA/132", destFile);
////        System.out.println(file);
//        String s = ImageToBase64.NetImageToBase64("http://thirdwx.qlogo.cn/mmopen/vi_32/OTZ1icFh69VFt7FbL2a7t8lFMT7jFthl5ibDicSST6JOCCxt5X3SZuw9icicJ7YIjib0pw0Bf0ct1RXzXfj2dn6RJkgA/132");
//        boolean b = GenerateImage(s, destFile+"\\aaa.jpg");
//        System.out.println(b);
//    }

    public static String savePhoto(String uri){
        try {
            String name = String.valueOf(new Date().getTime())+".jpg";
            GenerateImage(ImageToBase64.NetImageToBase64(uri),destFile+name);
            return destUrl+name;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
